package com.platform.modular.interceptor;

import com.platform.common.model.Result;
import com.platform.common.utils.JsonUtils;
import com.platform.modular.feign.account.MerchantFeignService;
import com.platform.modular.feign.model.entity.MerchantEntity;
import com.platform.modular.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yifei.han
 * @version 1.0
 * @className AppIdHanlderInterceptor
 * @description
 * @date 2022/3/11
 */
@Component
public class AppIdHanlderInterceptor implements HandlerInterceptor {

    @Lazy
    @Autowired
    private MerchantFeignService merchantFeignService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String appId = request.getHeader("appId");
        if (StringUtils.isBlank(appId)) {
            response.setContentType("application/json");
            String result = JsonUtils.objectToJson(Result.fail("AppId不能为空"));
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(result);
            return false;
        }
        Object appIdValue = redisUtil.get("accout:merchant_id:" + appId);
        if (appIdValue == null) {
            MerchantEntity merchantEntity = merchantFeignService.queryMerchantByAppId(appId);
            if (merchantEntity == null) {
                response.setContentType("application/json");
                String result = JsonUtils.objectToJson(Result.fail("错误的AppId"));
                response.getWriter().write(result);
                return false;
            }
            redisUtil.set("accout:merchant_id:" + appId, merchantEntity.getAppId());
        }
        return true;
    }


}
